﻿Imports Trinkets.Core

Public MustInherit Class BaseWindowHandler

    Protected _window As Window = Nothing

    Protected _grid As Grid = Nothing

    Protected _database As CsvDatabase = Nothing

    Protected _table As TableSchema = Nothing

    Private _menu As Menu = Nothing

    Protected Sub New(ByVal table As TableSchema, _
                      ByVal database As CsvDatabase, _
                      ByVal title As String, _
                      ByVal width As Integer, _
                      ByVal height As Integer)

        _grid = New Grid()

        _window = New Window
        _window.Width = width
        _window.Height = height
        _window.WindowStartupLocation = WindowStartupLocation.CenterScreen
        _window.Title = title
        _window.Tag = Me
        _window.Content = _grid

        _database = database

        _table = table

    End Sub

    Public Function ShowDialog() As Boolean?
        Return _window.ShowDialog()
    End Function

    Public Sub AddMenuItem(ByVal category As String, _
                           ByVal itemCaption As String, _
                           Optional ByVal clickHandler As RoutedEventHandler = Nothing)

        ' Create a menu if one does not already exist
        If _menu Is Nothing Then
            _menu = New Menu
            _menu.Height = 22

            ' Create an outer grid that will hold the menu and the existing controls
            Dim Panel As New Grid
            Dim MenuRow As New RowDefinition
            MenuRow.Height = New GridLength(22)
            Dim ContentRow As New RowDefinition
            ContentRow.Height = New GridLength(22, GridUnitType.Star)
            Panel.RowDefinitions.Add(MenuRow)
            Panel.RowDefinitions.Add(ContentRow)
            _window.Content = Panel

            ' Add the menu
            Panel.Children.Add(_menu)
            Grid.SetRow(_menu, 0)

            ' Add the remaining controls
            Panel.Children.Add(_grid)
            Grid.SetRow(_grid, 1)

        End If

        ' Get the category item 
        Dim CategoryItem As MenuItem = Nothing
        For Each CandidateItem As MenuItem In _menu.Items
            If CandidateItem.Header = category Then CategoryItem = CandidateItem
        Next

        ' Create the category item if necessary
        If CategoryItem Is Nothing Then
            CategoryItem = New MenuItem
            CategoryItem.Header = category
            _menu.Items.Add(CategoryItem)
        End If

        ' Add the menu item
        Dim MenuItem As New MenuItem
        MenuItem.Header = itemCaption
        If clickHandler IsNot Nothing Then AddHandler MenuItem.Click, clickHandler
        CategoryItem.Items.Add(MenuItem)

    End Sub

End Class
